<?php
// +----------------------------------------------------------------------
// | 事件日志服务层
// +----------------------------------------------------------------------
// | 主要服务于事件日志数据处理
// +----------------------------------------------------------------------
// | 错误编码头 206xxx
// +----------------------------------------------------------------------
namespace common\service;

use common\model\UserModel;
use support\SingletonTrait;
use Webman\Stomp\Client;

class MessageService
{

    // 单例工具
    use SingletonTrait;

    public function __construct()
    {
    }

    /**
     * 发送系统通知消息
     * @param array $param 渲染参数
     * @param int $projectId 项目id
     * @param int $receiver 接收人
     * @param int $messageTemplateId 消息模板id
     * @param string $contentType 内容类型
     * @param array $actions 操作
     * @param string $noticeType 提示类型
     * @param int $isPopUp 是否弹出
     * @param string $messageKey 事件标识
     * @param array $extraData
     * @param array $messageDetailData
     * @return mixed
     * @throws \Exception
     */
    public function sendSystemNotifyMessage(array $param, int $projectId, int $receiver, int $messageTemplateId, $contentType = "card_message", $actions = [], $noticeType = 'examine', $isPopUp = 1, $messageKey = "", $extraData = [], $messageDetailData = [])
    {
        $messageTemplateService = MessageTemplateService::getInstance();
        $renderedTemplate = $messageTemplateService->renderMessage($param, $messageTemplateId);

        $data = [
            'project_id' => $projectId,
            'receiver' => $receiver,
            'type' => "normal",
            'content_type' => $contentType,
            'content' => [
                'title' => $renderedTemplate['title'],
                'content' => $renderedTemplate['content_rendered'],
                'content_pc' => $renderedTemplate['content_pc_rendered'],
                'type' => $noticeType,
                'urls' => $actions,
                'icon' => "",
                'message_key' => $messageKey,
                'extra_data' => $extraData,
            ],
            'is_popup' => $isPopUp ? "yes" : "no"
        ];

        return teamones_request('teamones-im', 'oauth/send_system_notice_message', ['data' => $data, 'detail_data' => $messageDetailData])['data'];
    }

    /**
     * 通知用户事件消息
     * @param int $userId
     * @param $eventKey
     * @param null $eventData
     * @param bool $isUnionId
     * @throws \Exception
     */
    public function notifyUserEvent(int $userId, $eventKey, $eventData = null, $isUnionId = false)
    {
        if (!$isUnionId) {
            $user = model(UserModel::class)->field('union_id')->find($userId);
            if (empty($user)) {
                trace("notify user [{$userId}] does not exist", 'ERR');
                return;
            }
            $userId = $user['union_id'];
        }
        $requestData = ['param' => [
            'filter' => [
                'id' => $userId,
            ],
            'data' => [
                'event_key' => $eventKey,
                'event_data' => $eventData
            ]
        ]];
        teamones_request('teamones-im', 'oauth/send_data_to_user_channel', $requestData);
    }

    /**
     * 通知用户任务状态更新
     * @param int $userId
     * @param int $taskId
     */
    public function notifyUserTaskStatusChanged(int $userId, int $taskId)
    {
        try {
            $this->notifyUserEvent($userId, 'task_status_updated', ['task_id' => $taskId]);
        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
    }

    /**
     * 发送系统通知消息
     * @param array $tplData
     * @param int $projectId 项目id
     * @param int $receiver 接收人
     * @param int $messageTemplateId 消息模板id
     * @param string $contentType 内容类型
     * @param string $noticeType 提示类型
     * @param int $isPopUp 是否弹出
     * @param string $messageKey 事件标识
     * @param array $messageDetailData
     * @return mixed
     */
    public function sendSystemNotifyMessageV2(array $tplData, int $projectId, int $receiver, int $messageTemplateId, $contentType = "card_message", $noticeType = 'examine', $isPopUp = 1, $messageKey = "", $messageDetailData = [])
    {
        $tpl = teamones_request('teamones-im', 'message_template/find', [
            'param' => [
                'filter' => [
                    'id' => $messageTemplateId
                ]
            ]
        ]);
        $tpl = $tpl['data']['config'];
        $data = [
            'project_id' => $projectId,
            'receiver' => $receiver,
            'type' => "normal",
            'content_type' => $contentType,
            'notify_type' => $noticeType,
            'content' => [
                'type' => $noticeType,
                'message_key' => $messageKey,

                'tpl' => $tpl,
                'tpl_data' => $tplData,
            ],
            'is_popup' => $isPopUp ? "yes" : "no"
        ];

        $requestData = [
            'data' => $data,
            'detail_data' => $messageDetailData,
        ];
        return teamones_request('teamones-im', 'oauth/send_system_notice_message', $requestData);
    }

    /**
     * 通知任务通用单行通知消息 entity
     * @param array $taskRelatePeoples
     * @param string $noteText
     * @param array $entity
     * @param string $messageKey
     * @return void
     */
    public function sendEntityCommonProducerAssistantMessage(array $taskRelatePeoples, string $noteText, array $entity, $messageKey = 'entity_has_change')
    {
        $templateId = OptionsService::getInstance()->getEntityTaskRemindCommonTemplateId();
        $notifyParam = [
            'first' => '任务信息变更',
            'note_text' => $noteText,
            'remark' => "请及时查看",
            'tenant_id' => $entity['tenant_id'],
            'project_id' => $entity['project_id'],
            'entity_id' => $entity['id'],
            'module_code' => in_array(module_by_id($entity['module_id'])['code'], ['design', 'level', 'asset']) ? 'design' : 'storyboard',
            'message_key' => $messageKey,
        ];
        foreach ($taskRelatePeoples as $people) {
            // 异步发送通知
            Client::send('send_notify_message_v2', build_queue_data_with_xu([
                "param" => $notifyParam,
                'receiver' => $people['union_id'],
                'template_id' => $templateId,
                'content_type' => 'card_message',
                'notice_type' => 'task_remind',
                'is_popup' => 1,
                'message_key' => $messageKey,
            ]));
        }
    }
}
